package org.jash.mdm

import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import io.virtualapp.hook_sdk.firewall.AppNetInfo
import io.virtualapp.hook_sdk.firewall.FireWallType
import io.virtualapp.hook_sdk.firewall.HookSDK
import kotlinx.coroutines.launch
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseActivity
import org.jash.common.mvi.BaseState
import org.jash.mdm.databinding.ActivityMainBinding
import org.jash.mdm.model.LockIntent
import org.jash.mdm.model.LockState
import org.jash.mdm.model.LockViewModel

@Route(path ="/main/main")
class MainActivity : BaseActivity<ActivityMainBinding, LockViewModel>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            viewModel.intent.send(LockIntent.CheckLocked(1))
        }
    }
    fun check(response:LockState.Response) {
        if (response.lockEntity.lockState) {
            Toast.makeText(this, "设备已锁请联系管理员解锁", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            HookSDK.Build()
                .init(this, packageName) { logDebug(it) }
                .configFireWall(FireWallType.WHITE,response.lockEntity.whites?.map {AppNetInfo("", it.url, "")} ?: listOf() )
                .build()
                .hook()
            logDebug(response.lockEntity.whites)
            lifecycleScope.launch {
                viewModel.intent.send(LockIntent.Start(5))
            }
        }
    }
    fun progress(progress:LockState.Progress) {
        binding.time.text = "倒计时: ${progress.v}s"
    }
    fun complete(finish:LockState.Finish) {
        ARouter.getInstance()
            .build("/launcher/frame")
            .withInt("userId", 1)
            .navigation()
        finish()
    }
    fun error(error:BaseState.Error) {
        Toast.makeText(this, error.msg, Toast.LENGTH_SHORT).show()
        logDebug(error.msg)
    }
}